package ga_yad2;


import genetic_algorithm.Chromosome;
import genetic_algorithm.FitnessFunction;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class Yad2Fitness implements FitnessFunction {

	static private List<Map<Character,Integer>> preferences;
	
	static public void initPreference(List<int[]> pref)
	{
		preferences = new LinkedList<Map<Character,Integer>>();
		for (int[] arr : pref)
		{
			HashMap<Character, Integer> map = new HashMap<Character, Integer>();
			for (int i = 0 ; i < 10 ; ++i)
			{
				map.put((char)(i+97), arr[i]);
			}
			// TODO DEBUG PRINT
			System.out.println(map);
			preferences.add(map);
		}
	}

	@Override
	public double getFitness(Chromosome chromosome) {
		
		int fitness = 0;

		// calculate satisfaction for each person
		int numPersons = Yad2Chromosome.productsSplit.size();
		for (int currPerson = 0 ; currPerson < numPersons ; ++currPerson)
		{
			// sum preference of each owned product
			fitness += getFitnessOfOnePerson(chromosome, currPerson);
		}
		
		return fitness;
	}
	
	public static int getFitnessOfOnePerson(Chromosome chromosome, int personIndex)
	{
		// initialize fitness value
		int fitness = 0;
		
		// set person's offset within products allocation
		int offset = Yad2Chromosome.productsSplit.get(personIndex)[Yad2Chromosome.START];
		
		// number of products owned by person
		int numProducts = Yad2Chromosome.productsSplit.get(personIndex)[Yad2Chromosome.AMOUNT];
		
		// sum preference of each owned product
		for (int currProduct = offset; currProduct < offset + numProducts; ++currProduct)
		{
			fitness += preferences.get(personIndex).get(
					(Character) chromosome.getValue(currProduct));
		}	
		return fitness;
	}

	public static int getFitnessOfOneProduct(int personIndex, Character product) {
		return preferences.get(personIndex).get(product);
	}
	
// TODO ORIGINAL	
//	@Override
//	public double getFitness(Chromosome chromosome) {
//		
//		int fitness = 0;
//
//		// for each person
//		for (int i = 0 ; i < Yad2Chromosome.productsSplit.size() ; ++i)
//		{
//			// sum preference of each owned product
//			for(int j = Yad2Chromosome.productsSplit.get(i)[Yad2Chromosome.START] 
//					; j < Yad2Chromosome.productsSplit.get(i)[Yad2Chromosome.AMOUNT] ; ++j)
//			{
//				fitness += preferences.get(i).get((Character)chromosome.getValue(j));
//			}
//		}
//		
//		return fitness;
//	}
//	
//	public static int getFitnessOfOnePerson(Chromosome chromosome, int index)
//	{
//		int fitness = 0;
//		for(int j = Yad2Chromosome.productsSplit.get(index)[Yad2Chromosome.START] 
//				; j < Yad2Chromosome.productsSplit.get(index)[Yad2Chromosome.AMOUNT] ; ++j)
//		{
//			fitness += preferences.get(index).get((Character)chromosome.getValue(j));
//		}	
//		return fitness;
//	}

}
